package com.yanfan.zutai.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.yanfan.common.core.text.Convert;
import com.yanfan.zutai.domain.BWeiXinUser;
import com.yanfan.zutai.domain.vo.BWeXinOpenId;
import com.yanfan.zutai.mapper.BWeiXinUserMapper;
import com.yanfan.zutai.service.IBWeiXinService;
import com.yanfan.zutai.service.IBWeiXinUserService;
import com.yanfan.zutai.util.Detect;
import com.yanfan.zutai.util.HttpPostAndGetUtil;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 公众号用户Service业务层处理
 *
 * @author ruoyi
 * @date 2023-04-11
 */
@Service
public class BWeiXinUserServiceImpl implements IBWeiXinUserService {
    @Autowired
    private BWeiXinUserMapper bWeiXinUserMapper;
    @Autowired
    private IBWeiXinService bWeiXinService;

    /**
     * 查询公众号用户
     *
     * @param id 公众号用户主键
     * @return 公众号用户
     */
    @Override
    public BWeiXinUser selectBWeiXinUserById(Long id) {
        return bWeiXinUserMapper.selectBWeiXinUserById(id);
    }

    /**
     * 查询公众号用户列表
     *
     * @param bWeiXinUser 公众号用户
     * @return 公众号用户
     */
    @Override
    public List<BWeiXinUser> selectBWeiXinUserList(BWeiXinUser bWeiXinUser) {
        return bWeiXinUserMapper.selectBWeiXinUserList(bWeiXinUser);
    }

    /**
     * 新增公众号用户
     *
     * @param bWeiXinUser 公众号用户
     * @return 结果
     */
    @Override
    public int insertBWeiXinUser(BWeiXinUser bWeiXinUser) {
        return bWeiXinUserMapper.insertBWeiXinUser(bWeiXinUser);
    }

    /**
     * 修改公众号用户
     *
     * @param bWeiXinUser 公众号用户
     * @return 结果
     */
    @Override
    public int updateBWeiXinUser(BWeiXinUser bWeiXinUser) {
        return bWeiXinUserMapper.updateBWeiXinUser(bWeiXinUser);
    }

    /**
     * 批量删除公众号用户
     *
     * @param ids 需要删除的公众号用户主键
     * @return 结果
     */
    @Override
    public int deleteBWeiXinUserByIds(Long[] ids) {
        return bWeiXinUserMapper.deleteBWeiXinUserByIds(ids);
    }

    /**
     * 删除公众号用户信息
     *
     * @param id 公众号用户主键
     * @return 结果
     */
    @Override
    public int deleteBWeiXinUserById(Long id) {
        return bWeiXinUserMapper.deleteBWeiXinUserById(id);
    }

    @Override
    public void insertOpenIdAndUser() {
        String url = "https://api.weixin.qq.com/cgi-bin/user/get";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("access_token", bWeiXinService.getToken()));
        String string = HttpPostAndGetUtil.doGet(url, params, "", "");
        JSONObject jsonObject = JSONObject.parseObject(string, JSONObject.class);
        if (jsonObject.get("data") != null) {
            BWeXinOpenId bWeXinOpenId = JSONObject.parseObject(jsonObject.get("data").toString(), BWeXinOpenId.class);
            for (int i = 0; i < bWeXinOpenId.getOpenid().length; i++) {
//                System.out.println(bWeXinOpenId.getOpenid()[i]);
                BWeiXinUser bWeiXinUser = new BWeiXinUser();
                bWeiXinUser.setOpenId(bWeXinOpenId.getOpenid()[i]);
                List<BWeiXinUser> bWeiXinUsers = selectBWeiXinUserList(bWeiXinUser);
                BWeiXinUser bWeiXin = this.openIdBindUserName(bWeXinOpenId.getOpenid()[i]);
                bWeiXinUser.setUserName(bWeiXin.getUserName());
                bWeiXinUser.setSubscribe(bWeiXin.getSubscribe());
                bWeiXinUser.setUpdateTime(new Date());
                if (bWeiXinUsers.size() > 0) {
                    bWeiXinUser.setId(bWeiXinUsers.get(0).getId());
                    if (Detect.notEmpty(bWeiXin.getUserName()) && !bWeiXin
                            .getUserName()
                            .equals(bWeiXinUsers.get(0).getUserName())) {
                        this.updateBWeiXinUser(bWeiXinUser);
                    }
                } else {
                    this.insertBWeiXinUser(bWeiXinUser);
                }
            }
        } else if (jsonObject.get("errcode") != null && Convert.toInt(jsonObject.get("errcode")) == 4001) {
            bWeiXinService.renovateToken();
        }
    }

    private BWeiXinUser openIdBindUserName(String openId) {
        BWeiXinUser bWeiXinUser = new BWeiXinUser();
        String url = "https://api.weixin.qq.com/cgi-bin/user/info";
        String userName = "";
        List<NameValuePair> params = new ArrayList<NameValuePair>();
        params.add(new BasicNameValuePair("access_token", bWeiXinService.getToken()));
        params.add(new BasicNameValuePair("openid", openId));
        params.add(new BasicNameValuePair("lang", "zh_CN"));
        String string = HttpPostAndGetUtil.doGet(url, params, "", "");
        JSONObject jsonObject = JSONObject.parseObject(string, JSONObject.class);
        if (jsonObject.get("openid") != null) {
            userName = jsonObject.get("remark").toString();
            bWeiXinUser.setUserName(userName);
            bWeiXinUser.setSubscribe(Convert.toInt(jsonObject.get("subscribe")));
        } else if (jsonObject.get("errcode") != null && Convert.toInt(jsonObject.get("errcode")) == 4001) {
            bWeiXinService.renovateToken();
        }
        return bWeiXinUser;
    }
}
